
import { Component, OnInit, ViewChild } from '@angular/core';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Rx';
//增删改查共通Service
import { CommService } from '../../comm/comm.service';
import { ReportUrls } from '../../comm/report.urls.conf';
import { QueryModel } from '../../model/report/query-model';
import 'rxjs/add/operator/toPromise';
declare const $: any;
import * as Enumerable from 'linq';
//import { debounce } from '_rxjs@5.5.5@rxjs/operators/debounce';
import { DxDropDownBoxComponent } from 'devextreme-angular';

@Component({
    selector: 'app-report-pun',
    templateUrl: './cmm.component.html',
    styleUrls: ['./cmm.component.scss']
})

export class CmmComponent implements OnInit {
    title = 'CMM状态分析';
    /*生产线 - 班次*/
    public subAreaItems = new Array();
    public equipemntItems = new Array();
    public subAareSelected: any;
    public equipmentSelected: any[];
    public cmmChartOption: any;
    public fwList: { endTime, intervalTime, intervalTime2, device, status, project, percent }[];
    public groupList: any[];
    public listCharts: any[];


    @ViewChild('dddb') dddb: DxDropDownBoxComponent;
    clearEquipmentSelected() {
        this.equipmentSelected = [];
    }

    constructor(private commServices: CommService) {
    }
    //组件初始化
    ngOnInit() {
        this.commServices.initDatePicker($('#DateTimeRange'), 'YYYY-MM-DD HH:mm');

        const queryModel: QueryModel = new QueryModel();
        this.commServices
            .getList(queryModel, ReportUrls.CmmProjects)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    model.data.forEach(e => {
                        this.subAreaItems.push(e);
                    });
                    this.subAareSelected = this.subAreaItems[0];
                } else if (model.resultCode === 300) {
                } else {
                    console.log(model.resultCode + ',' + model.resultMessage);
                }
            });

    }

    equipmentSelectedOk() {
        this.dddb.instance.close();
    }

    onSubAreaSelectedChange(subArea: { project: String }): void {
        const queryModel: QueryModel = new QueryModel();
        queryModel.tag = subArea.project;
        this.commServices
            .getList(queryModel, ReportUrls.CmmDevices)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    this.equipemntItems = [];
                    model.data.forEach(e => {
                        this.equipemntItems.push(e);
                    });
                    this.equipmentSelected = this.equipemntItems;
                } else if (model.resultCode === 300) {
                } else {
                    console.log(model.resultCode + ',' + model.resultMessage);
                }
            });
    }
    /**
     * 获取表格数据
     */
    getReportData(): void {
        const queryModel: QueryModel = new QueryModel();
        queryModel.dateTimeRange = this.getTime('DateTimeRange');
        queryModel.querySubAreaIds = [this.subAareSelected.project];
        queryModel.queryResourceIds = this.equipmentSelected.map(e => e.device);
        this.commServices
            .getList(queryModel, ReportUrls.CmmStatusList)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    model.data.forEach(e => {
                        e.intervalTime2 = ((e.intervalTime / 60).toFixed(2));
                        if (e.status === 'STR') {
                            e.status = '等待';
                        } else if (e.status === 'INS') {
                            e.status = '测量';
                        } else if (e.status === 'FLT') {
                            e.status = '故障';
                        } else if (e.status === 'BAD') {
                            e.status = '中断';
                        }
                    });
                    this.fwList = model.data;
                    this.listCharts = this.fwList;
                    this.showCharts(true);
                } else {
                    console.log(model.resultCode + ',' + model.resultMessage);
                }
            });
    }

    showCharts(reviewCharts: boolean) {
        // this.listCharts = this.fwList;
        // if (obj !== undefined) {
        //     const selected = obj.selected;
        //     const legend = obj.name;
        //     debugger
        //     if (this.listCharts.find(e => e.status === legend) !== undefined) {
        //         this.listCharts = this.listCharts.filter(e => e.status !== legend);
        //     } else {
        //     }
        // }
        const sumTime = Enumerable.from(this.listCharts).sum(e => e.intervalTime);
        this.groupList = Enumerable.from(this.listCharts).groupBy(u => u.status).select(u => {
            const temp = {
                device: u.first().device,
                status: u.first().status,
                intervalTime: u.sum(e => e.intervalTime),
                intervalTime2: (u.sum(e => e.intervalTime) / 60).toFixed(2),
                percent: ((u.sum(e => e.intervalTime) / sumTime) * 100).toFixed(2)
            };
            return temp;
        }).toArray();

        if (reviewCharts) {
            const x1 = new Array();
            const y1 = new Array();
            const yBar = new Array();

            this.groupList.forEach((e: { endTime, intervalTime, device, status, project }) => {
                debugger
                x1.push(e.status);
                const bean1 = { value: e.intervalTime, name: e.status };
                y1.push(bean1);
                yBar.push(e.intervalTime);
            });

            this.cmmChartOption = this.getOption(x1, y1, 'pie');
        }

    }

    getOption(x: any, y: any, type: String): any {

        const option = {
            title: {
                text: '',
                subtext: '',
                x: 'center'
            },
            tooltip: {
                trigger: 'item',
                formatter: (p) => {
                    return '状态:' + p.name + ' ，故障时间: ' + p.value + '分钟 ，占比:' + p.percent + '%' + '<br/>';
                },
            },
            legend: {
                orient: 'vertical',
                left: 'left',
                data: x
            },
            series: [
                {
                    name: 'CMM故障统计占比',
                    type: type,
                    radius: '55%',
                    center: ['50%', '60%'],
                    data: y,
                    itemStyle: {
                        emphasis: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };
        return option;
    }
    getTime(id: any): String {
        const timerange: String = $('#' + id).val();
        return timerange;
    }
    /**ECharts图表相关*/
    // tslint:disable-next-line:member-ordering
    chartsMap = new Map<any, any>();
    onChartInit(index: any, echartsIntance: any): void {
        this.chartsMap.set(index, echartsIntance);
        // echartsIntance.on('legendselectchanged', (obj) => {
        //     const selected = obj.selected;
        //     const legend: string = obj.name;
        //     this.showCharts(false, obj);
        // });
        Observable.fromEvent(window, 'resize')
            .debounceTime(100) // 以免频繁处理
            .subscribe(() => this.chartsMap.forEach((v) => v.resize()));
    }

    /**对页面数据进行导出 */
    protected exportData() {
        const files = new Array<any>();
        const queryModelArray = new Array<any>();

        queryModelArray.push('时间:' + this.getTime('DateTimeRange'));
        queryModelArray.push('区域:' + this.subAareSelected.project);
        let resourceStr = '';
        this.equipmentSelected.map(e => e.device).forEach(e => {
            resourceStr += e + ',';
        });
        queryModelArray.push('设备:' + resourceStr);
        this.chartsMap.forEach((v, k) => {
            const picBase64Info = v.getDataURL();
            files.push({
                chartsTitle: k, chartsEncodeStr: picBase64Info
            });
        });


        const tables = new Array<any>();

        const row1 = new Array();
        this.groupList.forEach((e: { endTime, intervalTime, intervalTime2, device, status, project, percent }) => {
            const co = new Array();
            co.push(e.device);
            co.push(e.status);
            co.push(e.percent);
            co.push(e.intervalTime);
            co.push(e.intervalTime2);
            row1.push(co);
        });

        const table1 = {
            tableName: 'CMM故障统计占比分布列表',
            titles: ['设备', '状态', '百分比(%)', '间隔时间(S)', '间隔时间(Min)'],
            rows: row1
        };

        tables.push(table1);

        this.commServices.exportPdf({
            reportTitle: this.title, charts: files, queryModel: queryModelArray, tables: tables
        });
    }

    onExporting(e) {
        e.fileName = e.fileName + new Date().toISOString().replace(/[\-\:\.]/g, '').split('T')[0];
    }
}
